'use strict';

const Service = require('egg').Service;

class Goods_photoService extends Service {
  async index(path, type) {
    try {
      const { GoodsPhoto } = this.app.model.Tables.Shop;
      if (typeof path === 'string') {
        const result = await GoodsPhoto.create({
          path,
          type,
          user_id: (this.ctx.adminInfo && this.ctx.adminInfo.id) || 0,
          project_id:
            (this.ctx.adminInfo && this.ctx.adminInfo.project_id) || 0,
        });
        console.log(result);
        if (result) {
          return this.ctx.response.success('添加成功', {
            id: result.id,
            path: result.path,
          });
        }
      } else {
        const arr = [];
        let i = 0;
        while (path[i]) {
          await GoodsPhoto.create({
            path: path[i],
            type,
            user_id: (this.ctx.adminInfo && this.ctx.adminInfo.id) || 0,
            project_id:
              (this.ctx.adminInfo && this.ctx.adminInfo.project_id) || 0,
          }).then((res) => {
            arr.push({
              id: res.id,
              path: res.path,
            });
          });
          i++;
        }
        return this.ctx.response.success('添加成功', arr);
      }

      return this.ctx.response.error('添加失败');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  // 更新图片信息 type 1商品，2评价, 3轮播图
  async update(point_id, photo_ids, type) {
    const { GoodsPhoto } = this.app.model.Tables.Shop;
    const arr = photo_ids.toString().split(',');
    let i = 0;
    const tempArr = [];
    try {
      // 查找到商品id的所有图片，把这些图片的商品id清空，
      const allGoodsPhoto = await GoodsPhoto.findAll({
        where: {
          point_id,
          type,
        },
      });
      let j = 0;
      while (allGoodsPhoto[j]) {
        await allGoodsPhoto[j].update({
          point_id: null,
        });
        j++;
      }

      // 遍历图片组id，找个每个图片给它添加商品id
      while (arr[i]) {
        const result = await GoodsPhoto.findByPk(arr[i]);
        if (result && result.dataValues) {
          const resultUpdate = await result.update(
            {
              point_id: point_id,
              type: type,
            }
            // , {
            //   where: {
            //     id: result.dataValues.id
            //   }
            // }
          );
          resultUpdate > 0
            ? console.log('更新该图片信息成功')
            : console.log('更新该图片信息失败');
          tempArr.push(resultUpdate);
        } else {
          console.log('找不到该图片');
        }
        i++;
      }
      return tempArr;
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
}

module.exports = Goods_photoService;
